package cn.water.luban.demo.gateway.filter;

import com.alibaba.nacos.common.utils.CollectionUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

@Component
public class MyFilter1 implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("过滤器[1]开始工作了");
        ServerHttpRequest request = exchange.getRequest();
        //1.完整的路径
        URI uri = request.getURI();
        System.out.println("uri:"+uri);
        //2.请求路径
        RequestPath path = request.getPath();
        System.out.println("path:"+path);
        //3.请求参数
        MultiValueMap<String,String> queryParams = request.getQueryParams();
        List<String> ages = queryParams.get("age");
        if(CollectionUtils.isNotEmpty(ages)){
            System.out.println("age:"+ages);
        }
        //4.请求头
        HttpHeaders headers = request.getHeaders();
        System.out.println("header:"+headers);
        List<MediaType> accept = headers.getAccept();
        System.out.println("accept:"+accept);
        String userAgent = headers.getFirst("User-Agent");
        System.out.println("userAgent:"+userAgent);
        //获取没有封装方法的头
        List<String> authorization = headers.get("Authorization");
        //5.获取请求客户端的ip地址
        request.getRemoteAddress();
        //6.请求cookie的数值
        request.getCookies();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
